(function() {
    // 记住账号密码自动登录
    if (!_isWX) {
        var login_data = {
            name: LS.get("cache_user_login_name"),
            password: LS.get("cache_user_login_pwd")
        };
        if (login_data.name && login_data.password) {
            coAjax.post(appConfig.user.sign_in_url, login_data, function success(result) {
                App.set("loginer", result.result);
                LS.set("cache_user_login_name", login_data.name);
                LS.set("cache_user_login_pwd", login_data.password);
            });
        };
        /*
        globalGet("WEIXIN_OPENID:" + busInfo._id, function(openid) {
        	if (!openid) {
        		return;
        	};
        	coAjax.get(appConfig.user.loginer, function(user_result) {
        		_wx_openid_login(openid);
        		alert("success", "微信验证自动登录成功");
        	}, function(errorMsg) {
        		var jumpHandle = Path.jump;
        		alert("error", errorMsg);
        		if (errorMsg === "refresh_token time out") {
        			jumpHandle = Path.wxJump;
        		}
        		if (location.host.indexOf("i-zhubao.com") > -1) {
        			myConfirm("您已绑定微信，是否自动认证登陆？", function() {
        				alert("success", "您已绑定微信，正在为您认证登陆");
        				var cb_url = encodeURIComponent(location.href);
        				jumpHandle("http://jewel.dotnar.com/weixin_login.html?cb_url=" + cb_url);
        			});
        		};
        	});
        });
        */
    };


    var _title_map = {
        "/main": "首页",
        "/goods_list": {
            key: "id",
            value_map: {
                "*": "最新上架",
                "2": "销量最高",
            }
        },
        "/storeinfo": "简介",
        "/cart": "购物车",
        "/goods_details": "商品详情",
        "/pay": "评价管理",
        "/sign_in": {
            key: "id",
            value_map: {
                "*": "用户登录",
                "2": "用户注册"
            }
        }
    };

    function _AppReady_init() {
        var $window = $(window);
        $window.scroll(function() {
            if ($window.scrollTop() > 220) {
                App.set("$Cache.main.top_bar_fill", true)
            } else {
                App.set("$Cache.main.top_bar_fill", false);
            };
        });
        Path.on(["/:page?", "/user/:page?"], function(_current_location) {
            var title_info = _title_map[Path._current_page];
            if (typeof title_info === "string") {
                App.set("Path.document_title", title_info);
            } else if (typeof title_info === "object") {
                var _val = Path.getQuery(title_info.key);
                App.set("Path.document_title", title_info.value_map[_val] || title_info.value_map["*"]);
            }
            if (_current_location.pathname.indexOf("/sign_in") < 0) {
                url = encodeURIComponent(location.href);
                App.set("$Cache.top.cb_url", url);
            };
            if (App.get("loginer")) {
                // 判断用户是否登陆，获取会员折扣
                App.set("$Cache.user.member_discount", Cookies.get("cache_user_member_discount"));
            };
            console.log("USER Document title:", App.get("Path.document_title"));
            // 错误的跳转
            if (Path._current_page.indexOf("/main-beta") > -1) {
                Path.jump("/main.html")
            };
        });

        // 搜索
        App.set("$Event.open_search", function() {
            var search_key = App.get("$Cache.search_text");
            if (!search_key) {
                myConfirm("请先输入搜索关键词！！！");
                return;
            };
            Path.jump("/searchset.html?q=" + search_key);
            App.set("$Cache.search_text", "");
            App.set("$Cache.top.is_show_search", false);
        });

        // 显示搜索框
        App.set("$Event.top.show_search_box", function() {
            App.model.toggle("$Cache.top.is_show_search");
        });

        // 添加到购物车
        App.set("$Event.goods_list.add_to_cart", function(e, vm) {
            console.log(vm.get("_id"));
            if (!App.get("loginer")) {
                myConfirm("添加商品前请先登陆！", function() {
                    Path.jump("/sign_in.html");
                });
            } else {
                var cart_item = {
                    goods_id: vm.get("_id"),
                    num: 1
                };
                goodsCart.add_to_cart(vm.get("_id"), 1, _get_cart_success)
            };
        });
        // 跳转到购物车
        App.set("$Event.top.jumpToCart", function() {
            if (!App.get("loginer")) {
                myConfirm("请先登陆后以访问购物车。", function() {
                    Path.jump("/sign_in.html?cb_url=" + App.get("$Cache.top.cb_url"));
                });
                return;
            };
            Path.jump("/cart.html");
        });
        // 头部按钮
        var _top_menu_timer;
        App.set("$Event.top.is_menu", function() {
            clearTimeout(_top_menu_timer);
            App.model.toggle("$Cache.top.is_menu");
            if (App.get("$Cache.top.is_menu")) {
                _top_menu_timer = setTimeout(function() {
                    App.set("$Cache.top.is_menu", false);
                }, 3500);
            };
        });
        // 返回顶部
        App.set("$Event.top.go_top", function() {
            $(document.body).animate({
                scrollTop: 0
            }, 300);
        });
        //处理用户信息：会员卡
        eventManager.is(App.get("loginer"), "getLoginer", function() {
            var card_id = App.get("loginer.card_list.0");
            if (card_id) {
                App.set("loginer.current_card_factory_id", card_id.split(/[\:\|]/)[3]);
            };
        });

        // 获取坐标
        // if (navigator.geolocation && (Path._current_page.indexOf("/weixin_login") < 0)) {
        //     navigator.geolocation.getCurrentPosition(function(position) {
        //         var coordinate = position.coords;
        //         App.set("$Cache.top.coordinate", position.coords);
        //         // 坐标获取天气
        //         var _url = "http://route.showapi.com/9-5?showapi_appid=7129&showapi_sign=aee1708ab21e4e0ba19d71aed4e3cf39&showapi_timestamp=" + init_time() + "&from=3&lat=" + coordinate.latitude + "&lng=" + coordinate.longitude;
        //         $.getJSON(_url, function(weatherResponse) {
        //             App.set("$Cache.user.localcity.weather", weatherResponse.showapi_res_body.now)
        //             App.set("$Cache.main.location_city", weatherResponse.showapi_res_body.cityInfo.c5);
        //         });
        //     }, function(error) {
        //         switch (error.code) {
        //             case error.TIMEOUT: // code==3
        //                 alert("warn", "gps连接超时，如需使用请刷新重试！");
        //                 break;
        //             case error.PERMISSION_DENIED: //code==1
        //                 alert("warn", "您已拒绝了使用gps位置共享服务，我们仅能由IP地址为您提供有限的位置服务");
        //                 break;
        //             case error.POSITION_UNAVAILABLE: // code==2
        //                 alert("warn", "亲爱的火星网友，非常抱歉，我们暂时无法为您所在的星球提供GPS位置服务");
        //                 break;
        //         };
        //         // 获取本机ip和城市信息
        //         var _url = "http://route.showapi.com/632-1?showapi_appid=7129&showapi_sign=aee1708ab21e4e0ba19d71aed4e3cf39&showapi_timestamp=" + init_time();
        //         $.getJSON(_url, function(ipResponse) {
        //             console.log(ipResponse.showapi_res_body.city);
        //             App.set("$Cache.main.location_city", ipResponse.showapi_res_body.city);
        //             var weather_url = "http://route.showapi.com/9-2?showapi_appid=7129&showapi_sign=aee1708ab21e4e0ba19d71aed4e3cf39&showapi_timestamp=" + init_time() + "&area=" + ipResponse.showapi_res_body.city;
        //             $.getJSON(weather_url, function(weatherResponse) {
        //                 console.log(weatherResponse.showapi_res_body);
        //                 App.set("$Cache.user.localcity.weather", weatherResponse.showapi_res_body.now);
        //             });
        //         });
        //     });
        // };

    };
    jSouper.App ? _AppReady_init() : eventManager.on("!AppReady", _AppReady_init);



    var goodsCart = {
        add_to_cart: function(goods_id, num, succ_cb, err_cb) {
            num = ~~num || 1;
            if (num < 0) {
                num = 0;
            };
            var cart_item = {
                goods_id: goods_id,
                num: 1
            };
            coAjax.post(appConfig.user.cart, cart_item, function(result) {
                alert("success", "商品已添加到购物车");
                succ_cb && succ_cb.apply(this, arguments);
            }, function(errorCode, xhr, errorMsg) {
                alert("error", errorMsg);
                err_cb && err_cb.apply(this, arguments);
            });
        }
    };

    function _get_cart_success(result) {
        var cart_detail = result.result;
        App.set("user.cart_detail", cart_detail);
        Path.jump("/cart.html");
    };

}());

// 获取时间戳函数
function init_time() {
    var now = new Date();
    var year = now.getFullYear();
    var month = ((now.getMonth() + 1) > 9) ? (now.getMonth() + 1) : ("0" + (now.getMonth() + 1));
    var days = now.getDate() > 9 ? now.getDate() : ("0" + now.getDate());
    var hours = now.getHours() > 9 ? now.getHours() : ("0" + now.getHours());
    var minutes = now.getMinutes() > 9 ? now.getMinutes() : ("0" + now.getMinutes());
    var seconds = now.getSeconds() > 9 ? now.getSeconds() : ("0" + now.getSeconds());
    return year + "" + month + "" + days + "" + hours + "" + minutes + "" + seconds;
};
